package com.honkentuber.chat;

import java.util.List;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;

import org.json.simple.JSONObject;

import com.google.appengine.api.datastore.KeyFactory;
import com.honkentuber.AppContext;

public class ChatServlet extends ChatBaseServlet {
  private static final long serialVersionUID = 2800778962458456034L;

  private final static Logger LOG =
      Logger.getLogger(ChatServlet.class.getName());

  private static Room getRoom(HttpServletRequest req, ChatDatabase db) {
    String roomKey = req.getParameter("roomKey");
    if (roomKey != null && roomKey.length() > 0) {
      Room room = db.fetchRoom(KeyFactory.stringToKey(roomKey));
      if (room == null) {
        LOG.warning("failed to fetch room: " + roomKey);
      } else {
        return room;
      }
    }
    return db.fetchDefaultRoom();
  }

  @Override
  protected String newJspResponse(AppContext ctx) {
    ChatContext chatCtx = (ChatContext) ctx;
    ChatDatabase db = chatCtx.getChatDb();
    Room room = getRoom(ctx.req, db);
    List<Message> msgs = db.storeAndFetchMessages(ctx.user, room,
        ctx.req.getParameter("msg"), getSequenceNumber(ctx.req));

    // if ("1".equals(ctx.req.getParameter("form"))) {
      ctx.req.setAttribute("room", room);
      ctx.req.setAttribute("msgs", msgs);
      return "/chatform.jsp";
    // }

    // TODO(ptucker):
    //    ctx.req.setAttribute("userJson", ctx.user == null
    //        ? "null" : ctx.user.getKey());
    //    ctx.req.setAttribute("userCacheJson",
    //        ctx.db.getUserCache().toJson().toJSONString());
    //    ctx.req.setAttribute("roomJson", room.toJson().toJSONString());
    //    ctx.req.setAttribute("msgsJson",
    //        Message.toJsonArray(msgs).toJSONString());
    // return "chat.jsp";
  }

  @SuppressWarnings("unchecked")
  protected JSONObject newJsonResponse(AppContext ctx) {
    ChatContext chatCtx = (ChatContext) ctx;
    ChatDatabase db = chatCtx.getChatDb();
    Room room = getRoom(ctx.req, db);
    List<Message> msgs = db.storeAndFetchMessages(ctx.user, room,
        ctx.req.getParameter("msg"), getSequenceNumber(ctx.req));

    // Build response, a single array msgs.
    JSONObject jsonResponse = new JSONObject();
    jsonResponse.put("room", room.toJson());
    if (!msgs.isEmpty()) {
      jsonResponse.put("msgs", Message.toJsonArray(msgs));
    }
    return jsonResponse;
  }

  private static Long getSequenceNumber(HttpServletRequest req) {
    try {
      return Long.parseLong(req.getParameter("seq"));
    } catch (Exception ex) {
      return null;
    }
  }
}